package com.gewu.pm.widget;

import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.LinearInterpolator;

import androidx.annotation.Nullable;

import com.gewu.pm.bean.ClockInStatisticsBean;

import java.util.ArrayList;
import java.util.List;

/**
 * 自定义圆形进度控件
 * 支持多段进度显示和动画效果
 */
public class CircularProgressView extends View {

    private Paint mBackgroundPaint;
    private Paint mProgressPaint;
    private RectF mRectF;
    
    private float mRadius = 100f;
    private float mAnimatedProgress = 0f;
    
    private List<ProgressSegment> mSegments = new ArrayList<>();
    private ValueAnimator mAnimator;
    
    // 动画相关
    private static final int ANIMATION_DURATION = 1000; // 1秒动画
    private static final float START_ANGLE = -90f; // 从12点钟方向开始

    public CircularProgressView(Context context) {
        super(context);
        init();
    }

    public CircularProgressView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public CircularProgressView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        // 背景画笔（饼图背景）
        mBackgroundPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mBackgroundPaint.setStyle(Paint.Style.FILL);
        mBackgroundPaint.setColor(Color.parseColor("#F5F5F5"));

        // 进度画笔（饼图扇形）
        mProgressPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mProgressPaint.setStyle(Paint.Style.FILL);

        mRectF = new RectF();
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        
        int size = Math.min(w, h);
        mRadius = size / 2f - 10; // 留一点边距
        
        float centerX = w / 2f;
        float centerY = h / 2f;
        
        mRectF.set(
            centerX - mRadius,
            centerY - mRadius,
            centerX + mRadius,
            centerY + mRadius
        );
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        
        // 绘制背景圆形
        canvas.drawCircle(getWidth() / 2f, getHeight() / 2f, mRadius, mBackgroundPaint);
        
        // 绘制饼图扇形
        if (!mSegments.isEmpty()) {
            float currentAngle = START_ANGLE;
            float totalAnimatedAngle = 360f * mAnimatedProgress; // 总的动画角度
            float drawnAngle = 0f; // 已绘制的角度
            
            for (ProgressSegment segment : mSegments) {
                float segmentTotalAngle = segment.percentage * 360f; // 该段应占的总角度
                
                if (drawnAngle < totalAnimatedAngle) {
                    // 计算当前段应该绘制的角度
                    float remainingAnimatedAngle = totalAnimatedAngle - drawnAngle;
                    float segmentDrawAngle = Math.min(segmentTotalAngle, remainingAnimatedAngle);
                    
                    if (segmentDrawAngle > 0) {
                        mProgressPaint.setColor(segment.color);
                        // 使用 true 参数绘制实心扇形（饼图效果）
                        canvas.drawArc(mRectF, currentAngle, segmentDrawAngle, true, mProgressPaint);
                    }
                }
                
                currentAngle += segmentTotalAngle;
                drawnAngle += segmentTotalAngle;
            }
        }
    }

    /**
     * 设置打卡统计数据并开始动画
     */
    public void setStatisticsData(ClockInStatisticsBean statistics) {
        if (statistics == null || statistics.getTotalCount() == 0) {
            mSegments.clear();
            invalidate();
            return;
        }

        mSegments.clear();
        
        // 按顺序添加各状态的进度段
        if (statistics.getLateCount() > 0) {
            mSegments.add(new ProgressSegment(
                statistics.getLateRate(),
                Color.parseColor(ClockInStatisticsBean.ClockInStatus.LATE.getColor())
            ));
        }
        
        if (statistics.getEarlyLeaveCount() > 0) {
            mSegments.add(new ProgressSegment(
                statistics.getEarlyLeaveRate(),
                Color.parseColor(ClockInStatisticsBean.ClockInStatus.EARLY_LEAVE.getColor())
            ));
        }
        
        if (statistics.getAbsentCount() > 0) {
            mSegments.add(new ProgressSegment(
                statistics.getAbsentRate(),
                Color.parseColor(ClockInStatisticsBean.ClockInStatus.ABSENT.getColor())
            ));
        }

        // 开始动画
        startAnimation();
    }

    /**
     * 开始绘制动画（从12点钟方向顺时醈1秒完成）
     */
    public void startAnimation() {
        if (mAnimator != null && mAnimator.isRunning()) {
            mAnimator.cancel();
        }

        mAnimator = ValueAnimator.ofFloat(0f, 1f);
        mAnimator.setDuration(ANIMATION_DURATION);
        mAnimator.setInterpolator(new LinearInterpolator());
        mAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                mAnimatedProgress = (float) animation.getAnimatedValue();
                invalidate();
            }
        });
        mAnimator.start();
    }

    /**
     * 重新绘制进度圈（带动画效果）
     */
    public void redrawWithAnimation() {
        startAnimation();
    }


    /**
     * 进度段数据类
     */
    private static class ProgressSegment {
        float percentage;  // 百分比 (0-1)
        int color;         // 颜色

        ProgressSegment(float percentage, int color) {
            this.percentage = percentage;
            this.color = color;
        }
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if (mAnimator != null && mAnimator.isRunning()) {
            mAnimator.cancel();
        }
    }
}
